<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 * @version		$Id:$
 */

class Modules_Core_Controllers_Plugins_AdminAuth extends Gio_Core_Plugin
{
	public function run()
	{
		$request = Gio_Core_Request::getInstance();
		$configs = Gio_Core_Config_Xml::getConfig('web');
		$adminPrefixUrl = $configs->admin->url_prefix;
		$adminTemplate  = $configs->admin->template;
		$adminSkin = (isset($configs->admin->skin)) ? $configs->admin->skin : 'default'; 

		$baseUrl = $request->getBaseUrl();
		$uri = $request->getRequestUri();
		$serverName = $request->getServerName();
		$serverPort = $request->getServerPort();
		$serverPort = ($serverPort == 80) ? '' : ':' . $serverPort;
		$uri = 'http://' . $serverName . $serverPort . $uri;
		$currentUrl = str_replace($baseUrl, '', $uri);
		$currentUrl = '/' . rtrim(ltrim($currentUrl, '/'), '/') . '/';
		
		/**
		 * 7 is length of /admin/
		 */
		$length = strlen($adminPrefixUrl) + 2;
		if (!$adminPrefixUrl || substr($currentUrl, 0, $length) != "/$adminPrefixUrl/") {
			return;
		}
		
		$controllerFront = Gio_Core_Controller::getIntance();
		$controllerFront->setTemplate($adminTemplate);
		
		$view = Gio_Core_View::getInstance();
		$view->APP_TEMPLATE = $adminTemplate;
		$view->APP_SKIN = $adminSkin;
		$view->setAdminSection(true);
		
		/**
		 * Check admin login
		 */
		$phpSessionId   = $request->getPost('PHPSESSID');
		$session = Gio_Core_Session::getSessionById($phpSessionId);
		
		$json = new Services_JSON();
		$user = (null == $session || null == $session['data']) 
										? null : $json->decode($session['data']);
		$view->userLogin = $user;
		//return;
		$route = Gio_Core_Route::getCurrentRoute(true);
		
		if ((null == $user || !isset($user->username) || null == $user->username)
				&& (null == $route || $route['name'] != 'core_auth_login')) 
		{
			$return = $_SERVER['REQUEST_URI'];
			$return = ($return) ? rawurlencode(base64_encode($return)) : null;
			$link = $view->url('core_auth_login');
			
			if (strpos($link, '?') !== false) {
				$return = ($return != null) ? '&return='.$return : null;
			} else {
				$return = ($return != null) ? '?return='.$return : null;
			}
			header('Location: '.$link . $return);
			exit();
		}
	}
	
}